// pages/index/index.js
const activityApi = require('../../api/activity.js')
const auth = require('../../utils/auth.js')

Page({
  data: {
    banners: [
      // 暂时注释掉，图片资源待添加
      // { id: 1, image: '/assets/images/banner1.jpg' },
      // { id: 2, image: '/assets/images/banner2.jpg' },
      // { id: 3, image: '/assets/images/banner3.jpg' }
    ],
    ongoingActivities: [],
    statistics: {
      total_activities: 0,
      total_registrations: 0,
      total_votes: 0
    },
    isLogin: false,
    isAdmin: false
  },

  onLoad() {
    this.loadData()
  },

  onShow() {
    // 检查登录状态和管理员身份
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      isLogin: auth.checkLogin(),
      isAdmin: userInfo && userInfo.role === 'admin'
    })
  },

  // 加载数据
  async loadData() {
    try {
      // 加载进行中的活动（静默请求，不显示错误）
      try {
        const activitiesRes = await activityApi.getActivityList({
          status: 'ongoing',
          limit: 3
        })
        
        if (activitiesRes && activitiesRes.code === 200) {
          this.setData({
            ongoingActivities: activitiesRes.data.items || []
          })
        }
      } catch (apiError) {
        console.log('API暂不可用，使用默认数据:', apiError.message || apiError)
        // API不可用时，显示空数据即可，不报错
        this.setData({
          ongoingActivities: []
        })
      }
      
      // 加载统计数据
      this.loadStatistics()
    } catch (error) {
      console.error('加载数据失败:', error)
      // 失败也不影响页面显示
    }
  },

  // 加载统计数据
  async loadStatistics() {
    try {
      const res = await activityApi.getStatistics()
      
      if (res.code === 200 || res.success) {
        this.setData({
          statistics: {
            total_activities: res.data.total_activities || 0,
            total_registrations: res.data.total_registrations || 0,
            total_votes: res.data.total_votes || 0
          }
        })
        console.log('📊 统计数据加载成功:', this.data.statistics)
      }
    } catch (error) {
      console.log('加载统计数据失败:', error.message || error)
      // 失败使用默认数据
      this.setData({
        statistics: {
          total_activities: 0,
          total_registrations: 0,
          total_votes: 0
        }
      })
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadData()
    wx.stopPullDownRefresh()
  },

  // 跳转到活动列表
  goToActivityList() {
    wx.switchTab({
      url: '/pages/activity/list/list'
    })
  },

  // 跳转到活动详情
  goToActivityDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/activity/detail/detail?id=${id}`
    })
  },

  // 跳转到我的报名
  goToMyRegistrations() {
    if (!auth.requireLogin()) return
    
    wx.navigateTo({
      url: '/pages/user/my-registrations/my-registrations'
    })
  },

  // 跳转到我的加油
  goToMyVotes() {
    if (!auth.requireLogin()) return
    
    wx.navigateTo({
      url: '/pages/user/my-votes/my-votes'
    })
  },

  // 创建活动
  goToCreateActivity() {
    if (!auth.requireLogin()) return
    
    wx.navigateTo({
      url: '/pages/admin/activity/edit/edit'
    })
  },

  // 跳转到管理后台（仅全局管理员）
  goToAdmin() {
    if (!auth.requireAdmin()) return
    
    wx.navigateTo({
      url: '/pages/admin/dashboard/dashboard'
    })
  },

  // 分享给好友/群聊
  onShareAppMessage() {
    return {
      title: '探索语言成长社 - 演讲活动管理',
      path: '/pages/index/index',
      imageUrl: '/assets/images/activity01.jpg'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '探索语言成长社 - 演讲活动管理',
      query: '',
      imageUrl: '/assets/images/activity01.jpg'
    }
  }
})

